<!-- SubtitleCalibrationDialog.vue -->
<template>
  <t-dialog
    v-model:visible="dialogVisible"
    header="字幕校准"
    width="90%"
    height="80vh"
    :confirm-btn="{ content: '保存并应用', theme: 'primary' }"
    :cancel-btn="{ content: '取消' }"
    @confirm="handleSave"
    @close="handleClose"
    class="subtitle-calibration-dialog"
  >
    <div class="calibration-content">
      <!-- 顶部工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <t-space>
            <t-input
              v-model="searchText"
              placeholder="搜索字幕内容..."
              clearable
              @change="handleSearch"
            >
              <template #suffix-icon>
                <SearchIcon />
              </template>
            </t-input>
            <t-select
              v-model="selectedLanguage"
              class="language-select"
              placeholder="目标语言"
              :options="languageOptions"
            >
            </t-select>
            <t-button theme="primary" @click="translateAllSubtitles" :loading="translating">
              <template #icon><t-icon name="translate" /></template>
              {{ translating ? '翻译中...' : '批量翻译' }}
            </t-button>
          </t-space>
        </div>
        <div class="toolbar-right">
          <t-space>
            <t-tag theme="default" variant="outline">总计: {{ subtitles.length }} 条</t-tag>
            <t-tag theme="success" variant="outline">已翻译: {{ translatedCount }}</t-tag>
            <t-tag theme="warning" variant="outline">待翻译: {{ untranslatedCount }}</t-tag>
          </t-space>
        </div>
      </div>

      <!-- 字幕列表 -->
      <div class="subtitle-list">
        <div class="list-header">
          <div class="header-cell id-cell">ID</div>
          <div class="header-cell time-cell">时间码</div>
          <div class="header-cell text-cell">原文</div>
          <div class="header-cell text-cell">译文</div>
          <div class="header-cell status-cell">状态</div>
          <div class="header-cell action-cell">操作</div>
        </div>

        <div class="list-body">
          <div
            v-for="(subtitle, index) in filteredSubtitles"
            :key="subtitle.id"
            class="subtitle-item"
            :class="{
              'translated': subtitle.text !== subtitle.originalText,
              'translating': subtitle.translating
            }"
          >
            <div class="item-cell id-cell">{{ subtitle.id }}</div>
            <div class="item-cell time-cell">
              <t-input
                v-model="subtitle.timeCode"
                size="small"
                @change="markAsModified(subtitle)"
              />
            </div>
            <div class="item-cell text-cell">
              <t-textarea
                v-model="subtitle.originalText"
                :autosize="{ minRows: 1, maxRows: 3 }"
                size="small"
                @change="markAsModified(subtitle)"
              />
            </div>
            <div class="item-cell text-cell">
              <t-textarea
                v-model="subtitle.text"
                :autosize="{ minRows: 1, maxRows: 3 }"
                size="small"
                :class="{ 'translated-text': subtitle.text !== subtitle.originalText }"
                @change="markAsModified(subtitle)"
              />
            </div>
            <div class="item-cell status-cell">
              <t-tag v-if="subtitle.translating" theme="primary" variant="light">
                <t-loading size="12px" />
                翻译中
              </t-tag>
              <t-tag v-else-if="subtitle.text !== subtitle.originalText" theme="success" variant="light">
                已翻译
              </t-tag>
              <t-tag v-else theme="default" variant="light">
                未翻译
              </t-tag>
            </div>
            <div class="item-cell action-cell">
              <t-space size="small">
                <t-button
                  size="small"
                  theme="primary"
                  variant="text"
                  @click="translateSingle(subtitle)"
                  :loading="subtitle.translating"
                  title="翻译此条"
                >
                  翻译
                </t-button>
                <t-button
                  size="small"
                  theme="default"
                  variant="text"
                  @click="resetSubtitle(subtitle)"
                  title="重置为原文"
                >
                  重置
                </t-button>
              </t-space>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="subtitles.length > pageSize">
        <t-pagination
          v-model="currentPage"
          v-model:pageSize="pageSize"
          :total="filteredSubtitles.length"
          :page-size-options="[10, 20, 50, 100]"
          size="small"
        />
      </div>
    </div>
  </t-dialog>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { SearchIcon } from 'tdesign-icons-vue-next'
import { translateSubs } from '@renderer/api/ttsApi'
import { Client } from '@renderer/client'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  captionPath: {
    type: String,
    required: true
  },
  itemName: {
    type: String,
    default: '未命名'
  }
})

const emit = defineEmits(['update:visible', 'save'])

// 响应式数据
const dialogVisible = ref(false)
const subtitles = ref([])
const searchText = ref('')
const selectedLanguage = ref('zh-CN')
const translating = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const modifiedSubtitles = new Set()

// 语言选项
const languages = [
  { code: 'en', name: '英语', flag: '🇺🇸' },
  { code: 'th', name: '泰语', flag: '🇹🇭' },
  { code: 'vi', name: '越南语', flag: '🇻🇳' },
  { code: 'zh-CN', name: '中文', flag: '🇨🇳' }
]

const languageOptions = computed(() =>
  languages.map((lang) => ({
    label: `${lang.flag} ${lang.name}`,
    value: lang.code
  }))
)

// 计算属性
const translatedCount = computed(() => {
  return subtitles.value.filter(s => s.text !== s.originalText).length
})

const untranslatedCount = computed(() => {
  return subtitles.value.length - translatedCount.value
})

const filteredSubtitles = computed(() => {
  if (!searchText.value) {
    return subtitles.value
  }

  const search = searchText.value.toLowerCase()
  return subtitles.value.filter(subtitle =>
    subtitle.originalText.toLowerCase().includes(search) ||
    subtitle.text.toLowerCase().includes(search) ||
    subtitle.timeCode.includes(search)
  )
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    loadSubtitles()
  }
})

watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 解析SRT格式
const parseSRT = (content) => {
  const blocks = content.trim().split(/\n\s*\n/)
  return blocks
    .map((block, index) => {
      const lines = block.trim().split('\n')
      if (lines.length >= 3) {
        const id = parseInt(lines[0]) || index + 1
        const timeCode = lines[1]
        const text = lines.slice(2).join('\n')
        return {
          id,
          timeCode,
          text,
          originalText: text,
          translating: false,
          modified: false
        }
      }
      return null
    })
    .filter(Boolean)
}

// 将字幕转换为SRT格式
const subtitlesToSRT = (subtitles) => {
  return subtitles
    .map((subtitle) => `${subtitle.id}\n${subtitle.timeCode}\n${subtitle.text}\n`)
    .join('\n')
}

// 解析翻译后的SRT格式
const parseTranslatedSRT = (translatedContent) => {
  const blocks = translatedContent.trim().split(/\n\s*\n/)
  const translatedSubtitles = []

  blocks.forEach((block) => {
    const lines = block.trim().split('\n')
    if (lines.length >= 3) {
      const id = parseInt(lines[0])
      const timeCode = lines[1]
      const text = lines.slice(2).join('\n')
      translatedSubtitles.push({
        id,
        timeCode,
        text
      })
    }
  })

  return translatedSubtitles
}

// 加载字幕文件
const loadSubtitles = async () => {
  if (!props.captionPath) {
    MessagePlugin.error('字幕文件路径为空')
    return
  }

  try {
    // 使用Client API读取字幕文件
    const result = await Client.file.readSubtitleFile(props.captionPath)
    if (result.success) {
      const parsedSubtitles = parseSRT(result.data.content)
      console.log(parsedSubtitles)
      if (parsedSubtitles.length > 0) {
        subtitles.value = parsedSubtitles
        MessagePlugin.success(`成功加载 ${parsedSubtitles.length} 条字幕`)
      } else {
        MessagePlugin.error('字幕文件格式错误或为空')
      }
    } else {
      MessagePlugin.error(`读取字幕文件失败: ${result.error}`)
    }
  } catch (error) {
    console.error('加载字幕文件失败:', error)
    MessagePlugin.error(`加载字幕文件失败: ${error.message || '未知错误'}`)
  }
}

// 标记字幕已修改
const markAsModified = (subtitle) => {
  subtitle.modified = true
  modifiedSubtitles.add(subtitle.id)
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 翻译单条字幕
const translateSingle = async (subtitle) => {
  if (!subtitle.originalText.trim()) {
    MessagePlugin.warning('原文内容为空')
    return
  }

  subtitle.translating = true

  try {
    const response = await translateSubs(subtitle.originalText, 'auto', selectedLanguage.value)

    if (response && response.data) {
      subtitle.text = response.data
      markAsModified(subtitle)
      MessagePlugin.success('翻译成功')
    } else {
      throw new Error('翻译响应格式错误')
    }
  } catch (error) {
    console.error('翻译失败:', error)
    MessagePlugin.error(`翻译失败: ${error.message || '未知错误'}`)
  } finally {
    subtitle.translating = false
  }
}

// 批量翻译所有字幕
const translateAllSubtitles = async () => {
  if (subtitles.value.length === 0) {
    MessagePlugin.warning('没有字幕可翻译')
    return
  }

  translating.value = true

  // 将所有字幕设置为翻译中状态
  subtitles.value.forEach(subtitle => {
    subtitle.translating = true
  })

  try {
    // 将所有字幕转换为SRT格式
    const srtContent = subtitlesToSRT(subtitles.value.map(s => ({ ...s, text: s.originalText })))

    // 发送整体翻译请求
    const response = await translateSubs(srtContent, 'auto', selectedLanguage.value)

    if (response && response.data) {
      try {
        // 解析翻译后的SRT内容
        const translatedSubtitles = parseTranslatedSRT(response.data)

        // 更新原字幕的翻译内容
        subtitles.value.forEach((subtitle) => {
          const translated = translatedSubtitles.find(t => t.id === subtitle.id)
          if (translated) {
            subtitle.text = translated.text
            markAsModified(subtitle)
          } else {
            console.warn(`未找到ID ${subtitle.id} 的翻译`)
          }
        })

        MessagePlugin.success(`批量翻译完成！共翻译 ${translatedSubtitles.length} 条字幕`)
      } catch (parseError) {
        console.error('解析翻译结果失败:', parseError)
        MessagePlugin.error('翻译结果解析失败，请检查返回格式')
      }
    } else {
      throw new Error('翻译响应格式错误')
    }
  } catch (error) {
    console.error('批量翻译失败:', error)
    MessagePlugin.error(`批量翻译失败: ${error.message || '未知错误'}`)
  } finally {
    // 清除所有字幕的翻译中状态
    subtitles.value.forEach(subtitle => {
      subtitle.translating = false
    })
    translating.value = false
  }
}

// 重置字幕为原文
const resetSubtitle = (subtitle) => {
  subtitle.text = subtitle.originalText
  subtitle.modified = true
  modifiedSubtitles.add(subtitle.id)
  MessagePlugin.success('已重置为原文')
}

// 保存字幕
const handleSave = async () => {
  try {
    // 生成新的SRT内容
    const newSrtContent = subtitlesToSRT(subtitles.value)

    // 保存到原文件
    const result = await Client.file.saveCaption(props.captionPath, newSrtContent)

    if (result.success) {
      MessagePlugin.success('字幕保存成功')

      // 发送保存事件给父组件
      emit('save', {
        captionPath: props.captionPath,
        modifiedCount: modifiedSubtitles.size,
        totalCount: subtitles.value.length,
        translatedCount: translatedCount.value
      })

      dialogVisible.value = false
    } else {
      MessagePlugin.error(`保存失败: ${result.message}`)
    }
  } catch (error) {
    console.error('保存字幕失败:', error)
    MessagePlugin.error(`保存失败: ${error.message || '未知错误'}`)
  }
}

// 关闭对话框
const handleClose = () => {
  if (modifiedSubtitles.size > 0) {
    MessagePlugin.warning('用户取消修改')
  } else {
    dialogVisible.value = false
  }
}

// 导出方法供父组件使用
defineExpose({
  loadSubtitles,
  translateAllSubtitles
})
</script>

<style scoped>
.subtitle-calibration-dialog {
  .t-dialog__body {
    padding: 0;
  }
}

.calibration-content {
  height: 70vh;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--td-component-border);
  background: var(--td-bg-color-container);
}

.toolbar-left {
  flex: 1;
}

.toolbar-right {
  flex-shrink: 0;
}

.language-select {
  width: 140px;
}

.subtitle-list {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: var(--td-bg-color-page);
  border-bottom: 1px solid var(--td-component-border);
  font-weight: 600;
}

.list-body {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px;
}

.header-cell,
.item-cell {
  display: flex;
  align-items: center;
  padding: 0 8px;
}

.id-cell {
  width: 60px;
  justify-content: center;
}

.time-cell {
  width: 180px;
}

.text-cell {
  flex: 1;
  min-width: 200px;
}

.status-cell {
  width: 100px;
  justify-content: center;
}

.action-cell {
  width: 120px;
  justify-content: center;
}

.subtitle-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid var(--td-component-border);
  transition: background-color 0.2s;
}

.subtitle-item:hover {
  background: var(--td-bg-color-container);
}

.subtitle-item.translated {
  background: var(--td-success-color-1);
}

.subtitle-item.translating {
  background: var(--td-warning-color-1);
}

.translated-text {
  color: var(--td-success-color);
}

.pagination-container {
  padding: 16px;
  border-top: 1px solid var(--td-component-border);
  background: var(--td-bg-color-container);
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .text-cell {
    min-width: 150px;
  }
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .toolbar-right {
    align-self: center;
  }

  .subtitle-item {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .header-cell,
  .item-cell {
    width: 100%;
    justify-content: flex-start;
  }
}
</style>
